<template>
  <view class="order-container">
    <!-- 状态切换栏 -->
    <view class="status-bar">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="status-item"
        :class="{ active: currentTab === tab.status }"
        @tap="switchTab(tab.status)"
      >
        <text>{{ tab.text }}</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view 
      scroll-y 
      class="order-list"
      @scrolltolower="loadMore"
      @refresherrefresh="onRefresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
    >
      <!-- 空状态 -->
      <view v-if="orderList.length === 0" class="empty-state">
        <image src="/static/images/empty-order.png" mode="aspectFit"></image>
        <text>暂无相关订单</text>
      </view>

      <!-- 订单列表内容 -->
      <view v-else class="order-items">
        <view 
          v-for="order in orderList" 
          :key="order.id"
          class="order-item"
          @click="goToDetail(order.id)"
        >
          <!-- 商家信息 -->
          <view class="merchant-info">
            <text class="merchant-name">{{ order.merchantId }}</text>
            <text class="order-status">{{ order.statusText }}</text>
          </view>

          <!-- 商品信息 -->
          <view class="goods-list">
            <view 
              v-for="item in order.orderItems" 
              :key="item.id"
              class="goods-item"
            >
              <image class="goods-image" :src="item.productImg" mode="aspectFill"></image>
              <view class="goods-info">
                <view class="goods-name">{{ item.productName }}</view>
                <view class="goods-spec" v-if="item.specInfo">{{ formatSpecInfo(item.specInfo) }}</view>
                <view class="goods-price">
                  <text class="price">¥{{ item.price.toFixed(2) }}</text>
                  <text class="quantity">x{{ item.quantity }}</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 订单金额 -->
          <view class="order-amount">
            <text>共{{ order.totalQuantity }}件商品</text>
            <text>实付款：<text class="amount">¥{{ order.payAmount.toFixed(2) }}</text></text>
          </view>

          <!-- 订单操作 -->
          <view class="order-actions">
            <template v-if="order.status === 0">
              <button class="action-btn cancel" @click.stop="cancelOrder(order)">取消订单</button>
              <button class="action-btn primary" @click.stop="payOrder(order)">立即支付</button>
            </template>
            <template v-else-if="order.status === 2">
              <button class="action-btn primary" @click.stop="confirmOrder(order)">确认收货</button>
            </template>
            <template v-else-if="order.status === 3">
              <button class="action-btn" @click.stop="deleteOrder(order)">删除订单</button>
              <template v-if="order.hasReviewed">
                <text class="reviewed-text">已评价</text>
              </template>
              <template v-else>
                <button class="action-btn" @click.stop="goToReview(order)">去评价</button>
              </template>
              <button class="action-btn primary" @click.stop="buyAgain(order)">再次购买</button>
            </template>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="loading-state">
        <uni-load-more status="loading"></uni-load-more>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tabs: [
        { status: null, text: '全部' },
        { status: 0, text: '待付款' },
        { status: 1, text: '待发货' },
        { status: 2, text: '待收货' },
        { status: 3, text: '已完成' },
        { status: 4, text: '已取消' }
      ],
      currentTab: null,
      orderList: [],
      loading: false,
      isRefreshing: false,
      page: 1,
      pageSize: 10,
      hasMore: true
    }
  },

  onLoad(options) {
    // 如果有传入类型参数，则切换到对应标签
    if (options.type) {
      const status = parseInt(options.type)
      if (!isNaN(status) && this.tabs.some(tab => tab.status === status)) {
        this.currentTab = status
      }
    }
    this.loadOrders()
  },

  methods: {
    // 切换标签
    switchTab(status) {
      if (this.currentTab === status) return
      this.currentTab = status
      this.orderList = []
      this.page = 1
      this.hasMore = true
      this.loadOrders()
    },

    // 加载订单列表
    async loadOrders() {
      if (this.loading || !this.hasMore) return

      try {
        this.loading = true
        const params = {
          pageNum: this.page,
          pageSize: this.pageSize
        }
        
        // 只有在选择了具体状态时才添加状态参数
        if (this.currentTab !== null) {
          params.status = this.currentTab
        }

        const res = await this.$api.orders.list(params)

        if (res.data) {
          const { records, total } = res.data
          
          // 检查已完成订单的评价状态
          if (records && records.length > 0) {
            for (const order of records) {
              if (order.status === 3 && order.orderItems && order.orderItems.length > 0) {
                try {
                  // 获取第一个商品的评价状态
                  const firstItem = order.orderItems[0]
                  const reviewRes = await this.$api.product.comment.checkHasReviewed(
                    order.id,
                    firstItem.productId
                  )
                  order.hasReviewed = reviewRes.data
                } catch (error) {
                  console.error('检查评价状态失败:', error)
                  order.hasReviewed = false
                }
              }
            }
          }
          
          if (this.page === 1) {
            this.orderList = records
          } else {
            this.orderList = [...this.orderList, ...records]
          }
          this.hasMore = this.orderList.length < total
        }
      } catch (error) {
        console.error('加载订单列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        if (this.isRefreshing) {
          this.isRefreshing = false
        }
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true
      this.page = 1
      this.hasMore = true
      await this.loadOrders()
    },

    // 加载更多
    loadMore() {
      if (this.hasMore) {
        this.page++
        this.loadOrders()
      }
    },

    // 格式化规格信息
    formatSpecInfo(specInfo) {
      if (!specInfo) return '';
      try {
        const specs = JSON.parse(specInfo);
        return Object.values(specs).join(' ');
      } catch (e) {
        return specInfo;
      }
    },

    // 跳转到订单详情
    goToDetail(orderId) {
      uni.navigateTo({
        url: `/pages/order/detail/index?id=${orderId}`
      })
    },

    // 取消订单
    async cancelOrder(order) {
      try {
        await this.$api.orders.cancel(order.id)
        uni.showToast({
          title: '取消成功',
          icon: 'success'
        })
        this.onRefresh()
      } catch (error) {
        uni.showToast({
          title: error.message || '取消失败',
          icon: 'none'
        })
      }
    },

    // 支付订单
    payOrder(order) {
      uni.navigateTo({
        url: `/pages/order/pay/index?orderId=${order.id}`
      })
    },

    // 确认收货
    async confirmOrder(order) {
      try {
        await this.$api.orders.confirm(order.id)
        uni.showToast({
          title: '确认成功',
          icon: 'success'
        })
        this.onRefresh()
      } catch (error) {
        uni.showToast({
          title: error.message || '确认失败',
          icon: 'none'
        })
      }
    },

    // 删除订单
    async deleteOrder(order) {
      try {
        await this.$api.orders.delete(order.id)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        this.onRefresh()
      } catch (error) {
        uni.showToast({
          title: error.message || '删除失败',
          icon: 'none'
        })
      }
    },

    // 再次购买
    buyAgain(order) {
      const productItems = order.orderItems.map(item => ({
        productId: item.productId,
        quantity: item.quantity
      }))
      uni.navigateTo({
        url: `/pages/order/submit/index?productItems=${JSON.stringify(productItems)}`
      })
    },

    // 跳转到评价页面
    goToReview(order) {
      uni.navigateTo({
        url: `/pages/order/review/index?orderId=${order.id}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.status-bar {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  position: sticky;
  top: 0;
  z-index: 100;

  .status-item {
    flex: 1;
    text-align: center;
    position: relative;
    padding: 10rpx 0;

    text {
      font-size: 28rpx;
      color: #333;
    }

    &.active {
      text {
        color: #ff5500;
      }

      &::after {
        content: '';
        position: absolute;
        left: 50%;
        bottom: -10rpx;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background-color: #ff5500;
        border-radius: 2rpx;
      }
    }
  }
}

.order-list {
  flex: 1;
  height: 0;
}

.empty-state {
  padding: 100rpx 0;
  text-align: center;

  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }

  text {
    font-size: 28rpx;
    color: #999;
  }
}

.order-items {
  padding: 20rpx;
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;

  .merchant-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;

    .merchant-name {
      font-size: 28rpx;
      color: #333;
    }

    .order-status {
      font-size: 26rpx;
      color: #ff5500;
    }
  }

  .goods-list {
    padding: 20rpx 0;

    .goods-item {
      display: flex;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .goods-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
      }

      .goods-info {
        flex: 1;
        margin-left: 20rpx;

        .goods-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
        }

        .goods-spec {
          font-size: 24rpx;
          color: #999;
          margin-bottom: 10rpx;
        }

        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .price {
            font-size: 32rpx;
            color: #ff5500;
          }

          .quantity {
            font-size: 26rpx;
            color: #999;
          }
        }
      }
    }
  }

  .order-amount {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20rpx 0;
    border-top: 1rpx solid #f5f5f5;
    font-size: 26rpx;
    color: #666;

    .amount {
      color: #ff5500;
      font-size: 32rpx;
      margin-left: 10rpx;
    }
  }

  .order-actions {
    display: flex;
    justify-content: flex-end;
    padding-top: 20rpx;
    border-top: 1rpx solid #f5f5f5;
    align-items: center;

    .reviewed-text {
      font-size: 26rpx;
      color: #999;
      margin-right: 20rpx;
    }

    .action-btn {
      margin-left: 20rpx;
      padding: 0 30rpx;
      height: 60rpx;
      line-height: 60rpx;
      font-size: 26rpx;
      border-radius: 30rpx;
      background-color: #fff;
      border: 1rpx solid #ddd;
      color: #666;

      &.primary {
        background-color: #ff5500;
        border-color: #ff5500;
        color: #fff;
      }

      &.cancel {
        border-color: #999;
        color: #999;
      }
    }
  }
}

.loading-state {
  padding: 20rpx 0;
  text-align: center;
}
</style> 